require.config({
    paths: {
        'jquery': ['http://cdn.bootcss.com/jquery/2.2.4/jquery.min', '/js/lib/jquery.min'],
        'doT': '/js/lib/doT.min',
        'bootstrap': '/js/lib/bootstrap.min',
        'datetimepicker': '/js/lib/bootstrap-datetimepicker.min',
        'select2': '/js/lib/select2.min',
        'paginator': '/js/lib/bootstrap-paginator'
    },
    shim: {
        'bootstrap': ['jquery'],
        'paginator': ['bootstrap']
    }
});

require(['jquery', 'doT', 'common', 'select2', 'bootstrap', 'paginator'], function($, doT, common) {
    $(function() {
        var role = sessionStorage.getItem('role');
        var goodsList;
        var toImportList = [];
        var removeCurrentPage = 1;
        var school_id;
        $('#tab1').show();
        $('.addAll').hide();
        $('.removeAll').hide();
        $('.import').hide();
        if (role == 1) {
            $('.managerOnly').removeClass('managerOnly');
        }

        function getSchoolList() {
            $.getJSON(common.urlBase + '/school/allSchool.json', function(result) {
                var schoolTmpl = doT.template($('#schoolTmpl').text());
                $('#schoolSelect').html(schoolTmpl(result.data));
                $('#schoolSelect').select2();
            });
        }
        if (!(sessionStorage.getItem('role') == 2)) {
            getSchoolList();
        }

        function initPaginator(paginator, currentPage, numberOfPages, totalPages, event) {
            var options = {
                currentPage: currentPage,
                numberOfPages: numberOfPages,
                totalPages: totalPages,
                itemTexts: function(type, page, current) {
                    switch (type) {
                        case 'first':
                            return '首页';
                        case 'prev':
                            return '上一页';
                        case 'next':
                            return '下一页';
                        case 'last':
                            return '末页';
                        case 'page':
                            return page;
                    }
                },
                onPageChanged: event
            };
            paginator.bootstrapPaginator(options);
        }

        function selectChangePage(event, oldPage, newPage) {
            // alert('current page: ' + newPage);
            refreshGoodsList(newPage);
        }

        function selectedChangePage(event, oldPage, newPage) {
            refreshToImportList(newPage);
            removeCurrentPage = newPage;
        }

        $('.underLine').on('click', function(e) {
            if ($(e.currentTarget).children('a').attr('href') == '#tab1') {
                $(e.currentTarget).addClass('active').next().removeClass('active');
                $('#tab1').show();
                $('#tab2').hide();
            } else {
                $(e.currentTarget).addClass('active').prev().removeClass('active');
                $('#tab1').hide();
                $('#tab2').show();
            }
        });

        $('.import').on('click', function(e) {
            var d = {};
            var shopid = $('#shopSelect').val();
            d.itemList = toImportList;
            d.itemList.forEach(function (item) {
                item.shop_id=shopid;
            });
            console.log(d);
            $.ajax({
                url: common.urlBase + '/item/bulk_add.json',
                type: 'POST',
                crossDomain: true,
                contentType: 'application/json; charset=utf-8',
                dataType: 'json',
                data: JSON.stringify(d),
                success: function(res) {
                    if (res.ok) {
                        window.location.href = '/views/goods_manage.html';
                    }
                }
            });

        });

        $(document).on('click', '.addToImport', function(e) {
            var goods_id = $(e.currentTarget).attr('data-id');
            goodsList.obj.forEach(function(goods) {
                if (goods.num_iid == goods_id) {
                    if (toImportList.indexOf(goods) == -1) {
                        toImportList.push(goods);
                        refreshToImportList(removeCurrentPage);
                    }
                }
            });
            $(e.currentTarget).addClass('disabled');
        });
        $(document).on('click', '.removeToImport', function(e) {
            var goods_id = $(e.currentTarget).attr('data-id');
            toImportList.forEach(function(goods) {
                if (goods.num_iid == goods_id) {
                    toImportList.splice(toImportList.indexOf(goods), 1);
                    refreshToImportList(removeCurrentPage);
                }
            });
        });

        $('.addAll').on('click', function(e) {
            if (goodsList) {
                toImportList = toImportList.concat(goodsList.obj);
                refreshToImportList(removeCurrentPage);
                $('.addToImport').addClass('disabled');
            }
        });

        $('.removeAll').on('click', function(e) {
            toImportList = [];
            refreshToImportList(0);
            $('.import').hide();
            $('.addToImport').removeClass('disabled');
        });

        var pageSize = 10;

        function getGoods(page, size) {
            if (sessionStorage.getItem('school_id')) {
                school_id = sessionStorage.getItem('school_id');
            } else {
                school_id = $('#schoolSelect').val();
            }
            //获取学校的app_id和app_secret
            var app_id, app_secret;
            $.getJSON(common.urlBase + '/school/id-school/' + school_id + '.json', function(result) {
                app_id = result.data.appid;
                app_secret = result.data.appsecret;
                var url = common.urlBase + '/item/youzan/query.json?page_no=' + page + '&page_size=' + size + '&appid=' + app_id + '&appsecret=' + app_secret;

                $.getJSON(url, function(result) {
                    if (result.ok) {
                        clearSelectTable();
                        goodsList = result.data;
                        var selectTableTmpl = doT.template($('#selectTableTmpl').text());
                        $('#selectTable').html(selectTableTmpl(goodsList.obj));
                        $('.addAll').show();
                        if (toImportList.length) {
                            $('.import').show();
                        }
                        var total = goodsList.total_results;
                        $('#total').text(total);
                        var pageNumber = Math.ceil(total / pageSize);
                        common.initPaginator($('#paginator1'), page, 8, pageNumber, selectChangePage);
                    } else {
                        clearSelectTable();
                        $('#noticeMsg').text('查询失败~暂无商品');
                        $('#noticeModal').modal('show');
                    }

                });
            });

        }



        function refreshGoodsList(page) {
            getGoods(page, pageSize);
        }

        function refreshToImportList(page) {
            var p;
            $('#total2').text(toImportList.length);

            if (page !== 0) {
                p = page || 1;
                var pnum = Math.ceil(toImportList.length / pageSize);
                common.initPaginator($('#paginator2'), p, 8, pnum, selectedChangePage);
            } else {
                $('#paginator2').hide();
                $('.removeAll').hide();
            }
            var selectedTableTmpl = doT.template($('#selectedTableTmpl').text());
            $('#selectedTable').html(selectedTableTmpl(toImportList.slice((p - 1) * pageSize, p * pageSize)));
            if (toImportList.length) {
                $('.removeAll').show();
                $('.import').show();
            }
        }

        function clearSelectTable() {
            $('#selectTable').html('');
            toImportList = [];
        }

        $(document).on('click', '.goodsQuery', function(event) {
            refreshGoodsList(1);
            var sid;
            if (sessionStorage.getItem('school_id')) {
                sid = sessionStorage.getItem('school_id');
            } else {
                sid = $('#schoolSelect').val();
            }
            $.getJSON(common.urlBase + '/shop/school-shop/' + sid + '.json', function(result) {
                if (result.ok) {
                    var shopTmpl = doT.template($('#shopTmpl').text());
                    $('#shopSelect').html(shopTmpl(result.data));
                } else {
                    $('#noticeMsg').text('该学校还未添加饭堂，请先添加饭堂!');
                    $('#noticeModal').modal('show');
                    $('#shopSelect').html('');
                }
            });
        });

        if (sessionStorage.getItem('role') == 2) {
            refreshGoodsList(1);
            var sid;
            if (sessionStorage.getItem('school_id')) {
                sid = sessionStorage.getItem('school_id');
            } else {
                sid = $('#schoolSelect').val();
            }
            $.getJSON(common.urlBase + '/shop/school-shop/' + sid + '.json', function(result) {
                if (result.ok) {
                    var shopTmpl = doT.template($('#shopTmpl').text());
                    $('#shopSelect').html(shopTmpl(result.data));
                } else {
                    $('#noticeMsg').text('该学校还未添加饭堂，请先添加饭堂!');
                    $('#noticeModal').modal('show');
                    $('#shopSelect').html('');
                }
            });
        }
    });
});
